Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Getting "} is not a valid command name (r199)"

    Hello everyone,

    I’m running into persistent errors in Stata when using very simple code blocks that involve
    Code:
    while { ... }
    loops or
    Code:
    program define ... mata: ... end ... end
    . Despite the code being minimal and apparently correct, I keep getting messages such as:

    Code:
    cap program drop test_minimal
    program test_minimal
        version 18.0
        local a 1
        while (`a'<2) {
            mata:
                real matrix mymat = J(1,1,123)
            end
        local a = `a' + 1
        }
    end
    
    test_minimal
    I get:

    Code:
    } is not a valid command name
    r(199);
    However, this code works fine (all on a single line for Mata):

    Code:
    cap program drop test_minimal
    program test_minimal
        version 18.0
        local a 1
        while (`a'<2) {
            mata: real matrix mymat = J(1,1,123)
        local a = `a' + 1
        }
    end
    
    test_minimal
    But in my real code, I have a lot of Mata lines in that block. I’d like to do something like:

    Code:
     mata: <many lines of Mata code> end
    right in the middle of my while { ... } loop.
    Last edited by Hermelino Souza; 22 Dec 2024, 20:30. Reason: MATA

  • #2
    I'm guessing that this end
    Code:
    cap program drop test_minimal
    program test_minimal
        version 18.0
        local a 1
        while (`a'<2) {
            mata:
                real matrix mymat = J(1,1,123)
            end
            local a = `a' + 1
        }
    end
    prematurely ends your test_minimal program and so the closing brace is seen by Stata as stand-alone, without a corresponding opening brace.

    If your program is in a self-contained ado-file, then put your Mata code below the program's in the file, add a single entry-point function call to that executes everything that you want done, and call that single function in your program's internal Stata loop.

    If the program is in a do-file, then put the Mata code above the program, but otherwise follow that same strategy of a single point-of-entry function to be called in the program's loop.

    Edited to add: I think that there's also the possibility to use a
    Code:
    mata {
        <multiple lines of Mata code here>
    }
    construction, but as I recall other users have found that that can get tricky, and so I tend to go with the approach described above.
    Last edited by Joseph Coveney; 22 Dec 2024, 23:08.

    Comment

    Working...
    X